"use strict";
require(['mustache', "vw.config.template", 'vw.display', 'vw.query'], function(mustache, template, vw_display) {
	var $structure = $('#structure');
	var _themeID;

	$.ajax({
		type: "get",
		url: 'data/sysManage.json',
		dataType: "json",
		success: function(e) {
			var html = [
				'<ul class="list-group">',
				'	{{#group}}<li class="list-group-item" style="margin-bottom: 10px;">',
				'		<p class="text-primary"><strong>{{text}}</strong></p>',
				'		<ul>',
				'			{{#item}}<li style="margin: 10px 0;"><a id="{{id}}" href="#" {{#disable}}style="color: #F0F0F0;"{{/disable}}>{{text}}</a></li>{{/item}}',
				'		</ul>',
				'	</li>{{/group}}',
				'</ul>'
			].join('');

			$('#leftmenu').append(mustache.render(html, e));
			$("#leftmenu").on('click', 'li a', function(e) {
				var parentText = $(e.currentTarget).parents('ul').parent('li').find('p').text();
				$("#breadcrumb").html("<li><span class='fa fa-home'></span></li><li>" + parentText + "</li><li>" + e.currentTarget.innerText + "</li>");
			});

			initContent();
		}
	});

	function initContent() {
		$("#fn_log").on('click', function() {
			$structure.vw_query('destroy').vw_query({
				$container: $(".vw-content-container"),
				dataURL: VW_INTERFACE.WEBSERVICE.SystemManage("GetReportData"),
				queryURL: VW_INTERFACE.WEBSERVICE.SystemManage("GetSearchResult")
			}).vw_query("ajaxQueryData", "TB_BIZ_SYSTEM_LOG", "系统日志");
		});

		$("#fn_msg").on('click', function() {
			$structure.vw_query('destroy').vw_query({
				$container: $(".vw-content-container"),
				dataURL: VW_INTERFACE.WEBSERVICE.SystemManage("GetReportData"),
				queryURL: VW_INTERFACE.WEBSERVICE.SystemManage("GetSearchResult")
			}).vw_query("ajaxQueryData", "TB_BIZ_MAIL", "系统消息");
		});

		$("#fn_monitpr").on('click', function() {

			vw_common.customAjax({
				url: VW_INTERFACE.WEBSERVICE.SystemManage('GetCatalog'),
				type: "GET",
				dataType: "json",
			}, function(e) {
				$.each(e.data, function(k, val) {
					_themeID = val.id;
					vw_common.customAjax({
						url: VW_INTERFACE.WEBSERVICE.SystemManage('GetIndicators'),
						type: "GET",
						dataType: "json",
						data: {
							"catalogID": _themeID
						}
					}, function(e) {
						//						vw_display.init($structure, e.data);
						$structure.empty();
						$structure.css({
							'max-height': $(".vw-content-container").height() - 30 + "px",
							'overflow-y': 'auto',
							'overflow-x': 'hidden'
						});
						var rowindex = -1;
						var $container = $structure;
						for(var i = 0; i < e.data.length; i++) {
							if(e.data[i].row != rowindex) {
								rowindex = e.data[i].row;
								var html = mustache.render(template.display_row, {
									rowindex: rowindex
								});
								$structure.append(html);
								$container = $('#row_' + rowindex);
							}
							switch(e.data[i].type) {
								case "Text":
									drawText($container,e.data[i]);
									break;
								case "chart":
									drawChart($container, e.data[i]);
									break;
								case "Table":
									drawTable($container, e.data[i]);
									break;
								default:
							}
						}
					});
				});
			});
		});

		Resize();
		window.onresize = Resize;
	}

	function Resize() {
		$(".vw-left-container").css("height", $(window).height() - 100);
		$(".vw-content-container").css("height", $(window).height() - 100);
	}

	function drawTable($dom, data) {
		portlet($dom, data, {
			fnID: "vw-fn-download_" + data.id,
			fnIcon: "fa fa-download",
		});

		var cols = [];
		var formatfields = [];
		for(var i = 0; i < data.indiatorData.column.length; i++) {
			cols[i] = data.indiatorData.column[i];

			if(data.indiatorData.renderField) {
				if(data.indiatorData.renderField == cols[i]) {
					formatfields.push(i);
				}
			}
		}

		var rows = [];
		for(var i = 0; i < data.indiatorData.data.length; i++) {
			rows[i] = {};
			var cells = [];
			for(var j = 0; j < data.indiatorData.data[i].length; j++) {
				cells[j] = data.indiatorData.data[i][j].value;
				if(formatfields.indexOf(j) != -1) {
					cells[j] = formatter(cells[j]);
				}
			}
			rows[i].cells = cells;
		}
		var $table = $('#portlet_content_' + data.id);
		$table.append(mustache.render(template.display_table, {
			cols: cols,
			rows: rows
		}));

		$('#vw-fn-download_' + data.id).on('click', function() {
			var myDate = new Date();
			vw_common.downloadTable($table[0], myDate.toLocaleString());
		});
	}

	function drawDashBoard($dom, data) {
		var val = [];
		for(var i = 0; i < data.indiatorDatas.length; i++) {
			val[i] = {
				value: data.indiatorDatas[i].value,
				caption: data.indiatorDatas[i].caption,
				unit: data.indiatorDatas[i].unit
			};
		}

		var option = {
			colspan: data.colspan,
			color: data.style.color,
			icon: data.style.icon,
			title: data.title,
			indiatorData: val,
			id: data.id,
		}

		if(data.detail) {
			option.detail = {
				name: data.id,
			};
		}

		$dom.append(mustache.render(template.display_dashBoard, option));
	}

	function portlet($dom, data, fn) {
		var option = {
			colspan: data.colspan,
			style: data.style.style,
			color: data.style.color,
			icon: data.style.icon,
			title: data.style.title,
			id: data.id,
			fn: fn
		};

		if(data.detail) {
			option.detail = {
				name: data.id,
			};
		}

		$dom.append(mustache.render(template.display_portlet, option));
	}

	function drawText($dom, data) {
		portlet($dom, data, {});

		var val = [];
		for(var i = 0; i < data.indiatorData.length; i++) {
			val[i] = {
				value: data.indiatorData[i].value,
				caption: data.indiatorData[i].caption
			};
			if(data.indiatorData[i].is_show) {
				val[i].highlight = 'highlightSytle';
			}
		}
		var $text = $('#portlet_content_' + data.id);
		$text.append(mustache.render(template.display_text, {
			items: val
		}));
	};

	function drawChart($dom, data) {
		portlet($dom, data, {
			fnID: "vw-fn-download_" + data.id,
			fnIcon: "fa fa-download",
		});

		var $chartContainer = $('#portlet_content_' + data.id);
		$chartContainer.css("height", 400);

		require(['echarts'], function(echarts) {
			var $chart = echarts.init($chartContainer[0]);
			var option = {};

			switch(data.subtype) {
				case "Line_FlashingLineChart": //普通折线图
					option = normalBarAndLine(data.indiatorData, 'line');
					break;
				case "Pie_PieChart": //普通饼图1
					option = pirtwo(data.indiatorData, 'pie');
					break;
				default:
			}
			$chart.setOption(option);

			setInterval(function() {
				var cpu_username = [];
				var cpu_userval = [];
				var mem_username = [];
				var mem_userval = [];
				$.ajax({
					url: VW_INTERFACE.WEBSERVICE.SystemManage("GetIndicatorData"),
					type: 'post',
					dataType: 'json',
					data: {
						"catalogID": _themeID
					},
					success: function(e) {
						for(var i = 0; i < e.cpu.length; i++) {
							cpu_username = e.cpu[i].name
							var cpu_val = e.cpu[i].data
							cpu_userval = cpu_val.value
						}
						for(var i = 0; i < e.mem.length; i++) {
							mem_username = e.mem[i].name
							var mem_val = e.mem[i].data
							mem_userval = mem_val.value
						}
						if(option.legend.data == "CPU使用率") {
							option.xAxis[0].data.push(cpu_username);
							option.series[0].data.push(cpu_userval);
							if(option.series[0].data.length > 60) {
								option.series[0].data.shift();
								option.xAxis[0].data.shift();
							}
						}
						if(option.legend.data == "内存使用率") {
							option.xAxis[0].data.push(mem_username);
							option.series[0].data.push(mem_userval);
							if(option.series[0].data.length > 60) {
								option.series[0].data.shift();
								option.xAxis[0].data.shift();
							}
						}
						$chart.setOption(option);
					}
				});
			}, 1000);

			$('#vw-fn-download_' + data.id).on('click', function() {
				var myDate = new Date();
				vw_common.downloadChart($chart, myDate.toLocaleString());
			});
		})
	}

	function pirtwo(indiatorData, type, two_tyep) {
		var dataArr = indiatorData.data;
		var _chartColors = ["#0577a8", "#d74005", "#3bb516", "#ccce07", "#078c58", "#973f22"];

		var series = [],
			legend = [];
		for(var j = 0; j < dataArr.length; j++) {
			series.push({
				value: dataArr[j].value,
				name: dataArr[j].label,
				itemStyle: {
					color: _chartColors[j]
				}
			});
			legend.push(dataArr[j].label);
		}

		var option = {
			title: {
				text: '',
				subtext: '',
				x: 'center',
				show: false
			},
			calculable: true,
			legend: {
				data: legend,
				type: 'scroll',
				bottom: 10,
				show: true
			},
			series: [{
				name: " ",
				type: type,
				radius: ['5%', '60%'],
				center: ['50%', '40%'],
				roseType: two_tyep,
				sort: 'ascending',
				data: series,
				label: {
					show: true,
					length: 5,
					formatter: '{d}%'
				}
			}]
		};
		return option;
	}

	function normalBarAndLine(indiatorData, type) {
		var legend = [],
			xAxis = [],
			series = [];
		var _chartColors = ["#0577a8", "#d74005", "#3bb516", "#ccce07", "#078c58", "#973f22"];

		for(var i = 0; i < indiatorData.data.length; i++) {
			legend[i] = indiatorData.data[i].label;
			series[i] = {
				name: legend[i],
				type: type,
				itemStyle: {
					color: _chartColors[i],
				},
				data: []
			};
		}
		xAxis[0] = indiatorData.name;
		for(var j = 0; j < indiatorData.data.length; j++) {
			series[j].data[0] = indiatorData.data[j].value;
		}
		if(legend == "CPU使用率") {
			var option = {
				tooltip: {},
				legend: {
					data: legend,
					type: 'scroll'
				},
				xAxis: [{
						name: '0',
						type: 'category',
						axisTick: {
							show: false
						},
						axisLabel: {
							show: false
						},
						boundaryGap: false,
						data: xAxis
					},
					{
						name: '60秒',
						nameLocation: 'start',
						scale: true,
						axisTick: {
							show: false
						},
						axisLabel: {
							show: false
						}
					}
				],

				yAxis: {},
				series: series
			};
		} else if(legend == "内存使用率") {
			var option = {
				tooltip: {},
				legend: {
					data: legend,
					type: 'scroll'
				},
				xAxis: [{
						name: '0',
						type: 'category',
						axisTick: {
							show: false
						},
						axisLabel: {
							show: false
						},
						boundaryGap: false,
						data: xAxis
					},
					{
						name: '60秒',
						nameLocation: 'start',
						scale: true,
						axisTick: {
							show: false
						},
						axisLabel: {
							show: false
						}
					}
				],
				yAxis: {},
				series: series
			};
		}

		return option;
	}
});